#1、协程的原理：实现了堆栈指令上的惰性延迟的迭代器，通过send接口实现数据交互

#2、实现一个协程程序
#3、编写asyncio异步程序
#4、编写aiohttp异步请求网站接口


import asyncio
import time
import aiohttp

#协程程序
def sim_request():
    global value
    value = 0
    while True:
        print(f"value的值如下：")
        result = yield value
        print(f"result传送的值为:{result}")
        value += 1


#asyncio异步程序
class Response:
    status_code = 100


async def sim_request1():
    response = Response()
    await asyncio.sleep(0.5)
    print(f"本次response的结果为{response.status_code}")
    return response.status_code


#编写aiohttp异步请求网站接口
url_arry = ["https://www.126.com/"]*10


async def request_126(url):
    async with aiohttp.ClientSession() as session:#开启用户端与126建立链接
        async with session.get(url) as response: #传入url正式发出请求
            result1 = await response.text()
            return result1


if __name__ == "__main__":
    #协程的应用
    print("协程的应用执行结果如下：")
    s = sim_request()
    print(s)
    print("为result传参前：")
    print(next(s))
    print("为result传参后：")
    print(s.send(1))


# 编写asyncio异步程序
    print("编写asyncio异步程序执行结果如下：")
    task_arry = []
    for i in range(10):
        task_arry.append(sim_request1())
    loop = asyncio.get_event_loop()#建立异步环
    # loop.run_until_complete(asyncio.wait(task_arry))#等待异步执行结束
    result = loop.run_until_complete(asyncio.gather(*task_arry))
    # loop.close()#关闭异步环
    print("通过asyncio获取的期物如下：")
    print(result)
#编写aiohttp异步请求网站接口
    print("通过aiohttp请求126网站接口执行结果如下：")
    loop1 = asyncio.get_event_loop()
    task_arry1 = [request_126(url) for url in url_arry]
    result1 = loop1.run_until_complete(asyncio.gather(*task_arry1))
    loop1.close()
    print("以下为通过aiohttp请求126网站获取的结果")
    print(result1)